<#assign object = doc.objects>
package ${object.package}.service.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ${object.package}.service.Upgrade;
import ${object.package}.service.ModelViewService;
import redora.api.BusinessRuleViolation;
import redora.api.fetch.*;
import redora.configuration.rdo.model.RedoraConfiguration;
import redora.configuration.rdo.service.RedoraConfigurationUtil;
import redora.configuration.rdo.service.ServiceFactory;
import redora.util.BusinessRuleJSON;

public class RedoraServletBase extends HttpServlet {
	private Logger l = Logger.getLogger("${object.package}.service.base.RedoraServletBase");

    @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
        Upgrade upgrade = null;
        PrintWriter out = resp.getWriter();
		try {
            upgrade = new Upgrade();
			if (req.getParameter("_operationType").equals("getFieldsByObjectName")) {
				out.print('{');
				out.print("response:");
				out.print('{');
				out.print("status:0,data:");
				out.print('{');
				ModelViewService.getModelFields(req.getParameter("objectName"), out);
				out.print('}');
				out.print('}');
				out.print('}');
			} else if (req.getParameter("_operationType").equals("upgradeObjectTable")) {
				upgrade.upgradeTable(out, getServletContext());
			} else if (req.getParameter("_operationType").equals("dropAllTables")) {
				upgrade.dropAllTables();
				out.print('{');
				out.print("response:");
				out.print('{');
				out.print("status:0");
				out.print('}');
				out.print('}');
			} else if (req.getParameter("_operationType").equals("checkObjectField")) {
				upgrade.check(out);
			} else if (req.getParameter("_operationType").equals("getObjectCanFindFields")) {
				ModelViewService.getFindFields(req.getParameter("objectName"), out);
			} else if (req.getParameter("_operationType").equals("fetchRedoraScript")) {
				upgrade.initUpgradeScript();
				ServiceFactory.redoraConfigurationServiceJSON().findAll(Page.ALL_TABLE, out);
			} else if (req.getParameter("_operationType").equals("updateRedoraScript")) {
				RedoraConfiguration redoraConfiguration = ServiceFactory.redoraConfigurationServiceJSON().fromJson(RedoraConfigurationUtil.getJSONValue(req));
				Set<BusinessRuleViolation> ret = ServiceFactory.redoraConfigurationService().persist(redoraConfiguration);
				out.print('{');
				out.print("response:");
				out.print('{');
				if (ret.isEmpty()) {
					out.print("status:0,data:");
					out.print('{');
					RedoraConfigurationUtil.copy(redoraConfiguration, out);
				} else {
					out.print("status:-1,error:");
					out.print('{');
					BusinessRuleJSON.copy(ret, resp.getWriter());
				}
				out.print('}');
				out.print('}');
				out.print('}');
			} else if (req.getParameter("_operationType").equals("getScriptOutput")) {
				long id = Long.valueOf(req.getParameter("id"));
				ServiceFactory.redoraConfigurationServiceJSON().fetchLazy(id, resp.getWriter());
			} else if (req.getParameter("_operationType").equals("getObjectNames")) {
				ModelViewService.getModelNames(out);
			} else if (req.getParameter("_operationType").equals("dropTable")) {
				upgrade.dropTable(req.getParameter("objectName"));
				out.print('{');
				out.print("response:");
				out.print('{');
				out.print("status:0");
				out.print('}');
				out.print('}');
			}
            out.flush();
		} catch (Exception e) {
			resp.resetBuffer();
			out.print("{response:{");
			out.print("status:-2,error:");
			out.print('\"');
			out.print("I failed to process a JSON request: ");
			out.print(req.getParameter("_operationType"));
            out.print(". Reason: ");
            out.print(e.getMessage());
			out.print("\"}}");
			out.flush();
			l.log(Level.SEVERE, "I failed to process a JSON request: " + req.getParameter("_operationType"), e);
			throw new ServletException("I failed to process a JSON request: " + req.getParameter("_operationType"), e);
		} finally {
            try {
                if (upgrade != null) {
                    upgrade.close();
                }
            } catch (Exception e) {
                l.log(Level.WARNING, "Ignoring closing exception upgrade", e);
            }
        }
	}

    @Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
